#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

typedef int ElemType;
typedef struct DNode{
    struct DNode *prior;
    ElemType data;
    struct DNode *next;
}DNode, *DLinklist;

bool initList(DLinklist L);
DNode* getElem(DLinklist L, int index);
bool insertList(DLinklist L, int index, ElemType elem);
bool deleteList(DLinklist L, int index, ElemType *elem);
bool insertNextNode(DNode *p, ElemType elem);
bool insertPriorNode(DNode *p, ElemType elem);
void printList(DLinklist L);

int main(){
    DLinklist L;
    initList(L);
    insertList(L, 1, 10);
    // insertList(L, 2, 20);
    // insertList(L, 3, 100);
    printf("%d\n", getElem(L, 0)->data);
    printf("%d,%d\n", getElem(L, 1)->data);
    return 0;
}

bool initList(DLinklist L){
    L = (DNode *)malloc(sizeof(DNode));
    if(L==NULL) return false;
    L->next = NULL;
    L->prior = NULL;
    return true;
}

DNode* getElem(DLinklist L, int index){
    if(L==NULL||index<0) return NULL;
    DNode *p = L;
    int id = 0;
    while(p!=NULL&&id<index){
        p = p->next;
        id++;
    }
    return p;
}

bool insertList(DLinklist L, int index, ElemType elem){
    if(index<1) return false;
    DNode *p = getElem(L, index-1);
    insertNextNode(p, elem);
    return true;
}

bool deleteList(DLinklist L, int index, ElemType *elem){
    if(index<1) return false;
    DNode *p, *temp;
    p = getElem(L, index-1);
    if(p==NULL||p->next==NULL) return false;
    temp = p->next;
    *elem = temp->data;
    p->next = temp->next;
    temp->next->prior = temp->prior;
    free(temp);
    return true;
}

bool insertNextNode(DNode *p, ElemType elem){
    if(p==NULL) return false;
    DNode *temp = (DNode *)malloc(sizeof(DNode));
    if(temp==NULL) return false;
    temp->data = elem;
    temp->next = p->next;
    //问题在此段语句，去掉就可以运行？
    if(p->next!=NULL){
        //p->next->prior = temp;
    }
    p->next = temp;
    temp->prior = p;
    return true;
}

bool insertPriorNode(DNode *p, ElemType elem){
    if(p==NULL) return false;
    DNode *temp = (DNode *)malloc(sizeof(DNode));
    if(temp==NULL) return false;
    temp->data = p->data;
    temp->next = p->next;
    if(temp->next!=NULL){
        temp->next->prior = temp;
    }
    p->next = temp;
    p->data = elem;
    return true;
}

void printList(DLinklist L){
    if(L==NULL) return;
    DNode *p = L->next;
    while(p!=NULL){
        printf("%d\n", p->data);
        p = p->next;
    }
}